/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @param {TreeNode} p
 * @return {TreeNode}
 */
var inorderSuccessor = function(root, p) {
  return getNext(root, p.val);
};
function getNext(root, val) {
  var ans = null;
  var cur = root;
  while (cur !== null) {
    if (cur.val === val) {
      if (cur.right !== null) {
        ans = cur.right;
        while (ans.left !== null) ans = ans.left;
      }
      break;
    }
    if (val < cur.val) {
      if (ans === null || ans.val > cur.val) ans = cur;
      cur = cur.left;
    } else {
      cur = cur.right;
    }
  }
  return ans;
}